package com.firexxx.study.execmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {

    private static void shell(String cmd) {
        if (cmd == null || cmd.length() == 0) {
            return;
        }

        String[] cmds = new String[] {"sh", "-c", cmd};
        try {
            Process process = Runtime.getRuntime().exec(cmds);
            int value = process.waitFor();
            if (0 != value) {
                System.out.println("fail");

                return;
            }

            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            // System.out.println("[check] now size \n"+bs.readLine());
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[8192];
            for (int n; (n = in.read(b)) != -1;) {
                out.append(new String(b, 0, n));
            }
            System.out.println(out.toString());
            in.close();
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void executeLinuxCmd() {
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(is);

        while (true) {
            try {
                String cmd = br.readLine();
                if (cmd == null) {
                    continue;
                }

                if (cmd.equals("q")) {
                    System.out.println("exit");
                    break;
                }

                //System.out.println("got cmd job : " + cmd);
                shell(cmd);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            br.close();
            is.close();
        } catch (IOException e) {
        }

    }

    public static void main(String[] args) {
        //System.out.println("Hello World!");

        executeLinuxCmd();
    }
}
